#!/usr/bin/env php
<?php

if ($_SERVER['SCRIPT_NAME'] != 'script/generate') {
	echo 'please change directory to root and try "script/..." again', "\n";
	return false;
	exit();
}
handle_generate();




function handle_generate() {

	define('ROOT', $_SERVER['PWD'].'/');
	define('DS', DIRECTORY_SEPARATOR);

	$argvalues = $_SERVER['argv']; //note that $argv and $argc are set constants already $argv === $_SERVER['argv'] so they claim!
/*
	$modelName = 'Product';
	$controllerName = ucfirst($modelName) . 's'; // = Products
	$viewsFolder = strtolower($controllerName); //products

	$postvar = strtolower($modelName); // = product
	$singleExportVar = strtolower($modelName); // = product
	$singleLocalVar = $singleExportVar; // product
	$pluralExportVar = $singleExportVar . 's'; // = products

	$scaff = require('scaffold_controller');
	file_put_contents('apple.php', $scaff);
*/

	//$newclasstext = makeclasstext('Apple', array('index', 'list_items', 'show', 'new_item', 'edit', 'create', 'update', 'destroy'));
	//file_put_contents('apple.php', $newclasstext);


	array_shift($argvalues);
	switch (array_shift($argvalues)) {
	case 'model':
		if ($modelName = array_shift($argvalues)) {
			$modelName = ucfirst($modelName);
			makeModel($modelName);
		}
		else {
			echo 'Model name must be specified';
			return false;
		}
	break;
	case 'controller':
		if ($controllerName = array_shift($argvalues)) {
			$actions = $argvalues;
			makeController($controllerName, $actions);
		}
		else {
			echo 'No Controller name specified';
			return false;
		}
	break;
    case 'scaffold':
		if ($modelName = array_shift($argvalues)) {
			$modelName = ucfirst($modelName);
			makeModel($modelName);
			$controllerName =  ($controllerName = array_shift($argvalues)) ? ucfirst($controllerName) : ($modelName . 's');
			$actions = (isset(current($argvalues))) ? $argvalues : array('index', 'list_items', 'show', 'new_item', 'edit', 'create', 'update', 'destroy');
			makeController($controllerName, $actions);


			
			makeHelper($controllerName);
			echo $modelFile, "\n", $controllerFile, "\n";
			print_r($actions);
		}
		else {
			echo 'Atleast Model name must be specified', "\n";
			return false;
		}
	break;
	case 'migration':
		if ($argvalues[2]) {
			$migrationName = strtolower($argvalues[2]);
			makeMigration($migrationName);
		}
		else {
			echo 'No migration name specified';
			return false;
		}

	break;
    default:
       echo "you need to specify what you want to create; scaffold, model, controller, migration";
	}
}




function makeclasstext($modelName, $functionArray = array(), $extends = null) {
	$extends = ($extends) ? "extends {$extends} " : '';
	$functext = makefunctiontext($functionArray);
	$php_code = include('templates/snippets/class');
	return include('templates/snippets/php_braces');
}

function makefunctiontext($functionArray) {
	if (empty($functionArray)) { $functionArray = array(); }
	$text = '';
	foreach ($functionArray as $funct) { $text .= include('templates/snippets/function'); }
	return $text;
}

function makeModel($modelName) {
	//all models come with migration file
	$appDir = ROOT . 'application' . DS;
	check_or_create_dir($appDir);
	
	$modelDir = $appDir . 'classes' . DS;
	check_or_create_dir($modelDir);

	$modelFile = $modelDir . $modelName . '.php';
	$text = makeclasstext($modelName, null, 'M_ARB');
	create_file($modelFile, $text);


	$migrationName = 'create_' . strtolower($modelName);
	makeMigration($migrationName);
	//$migrationFile = '{schema number}_' . $migrationName . '.php';
}

function makeMigration($migrationName) {
	//$migrationFile = '{schema number}_' . $migrationName . '.php';
}

function check_or_create_dir($dir_path) {
	echo $dir_path, ' checking...', "\n";
	if (!is_dir($dir_path)) {
		echo $dir_path, ' making...', "\n";
		if (!mkdir($dir_path)) { exit('unable to make ' . $dir_path . "\n"); }
	}
	echo $dir_path, ' exists', "\n";
	return true;
}

function create_file($file_name, $contents = "\n") {
	//if (file_exists($file_name)) { exit($file_name . ' exists already! Please delete manually before creating new one'. "\n"); }
	if (!file_put_contents($file_name, $contents)) { exit($file_name . ' FAILED to create file' . "\n"); }
	echo $file_name, ' file generated successfully', "\n";
	return true;
}

function makeHelper($helperName) {
	$helperDir = $appDir . 'helpers' . DS;
	check_or_create_dir($helperDir);

	$helperFile = $helperDir . strtolower($helperName) . '_helper.php';
	$php_code = '// ' . $helperName . ' helper file';
	$text = include('templates/snippets/php_braces');
	create_file($helperFile, $text);
}


//05021003
//bml301025

function makeController($controllerName, $actions = array()) {

	$controllerName = ucfirst($controllerName);

	$appDir = ROOT . 'application' . DS;
	check_or_create_dir($appDir);
	
	$controllerDir = $appDir . 'controllers' . DS;
	check_or_create_dir($controllerDir);

	$viewsDir = $appDir . 'views' . DS;
	check_or_create_dir($viewsDir);

	$lowerCaseControllerName = strtolower($controllerName);

	$controllerViewsDir = $viewsDir . $lowerCaseControllerName . DS;
	check_or_create_dir($controllerViewsDir);

	$public_html = ROOT . 'public_html' . DS;
	check_or_create_dir($public_html);

	$stylesheetsDir = $public_html . 'stylesheets' . DS;
	check_or_create_dir($stylesheetsDir);

	$javascriptsDir = $public_html . 'javascripts' . DS;
	check_or_create_dir($javascriptsDir);

	$controllerStylesheetsDir = $stylesheetsDir . $lowerCaseControllerName . DS;
	check_or_create_dir($controllerStylesheetsDir);

	$controllerJavascriptsDir = $javascriptsDir . $lowerCaseControllerName . DS;
	check_or_create_dir($controllerJavascriptsDir);


	$controller_Name = $controllerName . '_controller';
	$controllerFile = $controllerDir . $controller_Name . '.php';
	$text = makeclasstext($controller_Name, $actions, 'Application_controller');
	create_file($controllerFile, $text);

	maheHelper($lowerCaseControllerName);

	$viewsNotToCreate = array('create', 'update', 'destroy');
	foreach ($actions as $actToCreate) {
		if (!in_array($actToCreate, $viewsNotToCreate)) {
			$text = "<h1>$actToCreate stub</h1>";
			$actionFile = $controllerViewsDir . $actToCreate . '.php';
			create_file($actionFile, $text);

			$stylesheetFile = $controllerStylesheetsDir . $actToCreate . '.css';
			create_file($stylesheetFile);

			$javascriptFile = $controllerJavascriptsDir . $actToCreate . '.js';
			create_file($javascriptFile);
		}
	}

}



?>


<?php
/*





                                                                                        
        Creates post model with predefined attributes.                                   
a@a-laptop:~/only_2_m_ror$                                                               
a@a-laptop:~/only_2_m_ror$ script/generate scaffold

Usage: script/generate scaffold ModelName [ControllerName] [action, ...]

Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.       

General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.     
    -q, --quiet                      Suppress normal output.            
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)

Description:
    The scaffold generator creates a controller to interact with a model.
    If the model does not exist, it creates the model as well.  The generated
    code is equivalent to the "scaffold :model" declaration, making it easy
    to migrate when you wish to customize your controller and views.

    The generator takes a model name, an optional controller name, and a
    list of views as arguments.  Scaffolded actions and views are created
    automatically.  Any views left over generate empty stubs.

    The scaffolded actions and views are:
        index, list, show, new, create, edit, update, destroy

    If a controller name is not given, the plural form of the model name
    will be used.  The model and controller names may be given in CamelCase
    or under_score and should not be suffixed with 'Model' or 'Controller'.
    Both model and controller names may be prefixed with a module like a
    file path; see the Modules Example for usage.

Example:
    ./script/generate scaffold Account Bank debit credit

    This will generate an Account model and BankController with a full test
    suite and a basic user interface.  Now create the accounts table in your
    database and browse to http://localhost/bank/ -- voila, you're on Rails!

Modules Example:
    ./script/generate scaffold CreditCard 'admin/credit_card' suspend late_fee

    This will generate a CreditCard model and CreditCardController controller
    in the admin module.

a@a-laptop:~/only_2_m_ror$
a@a-laptop:~/only_2_m_ror$





a@a-laptop:~/only_2_m_ror$ script/generate migration
Usage: script/generate migration MigrationName [options]

Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.

General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)

Description:
    The migration generator creates a stub for a new database migration.

    The generator takes a migration name as its argument.  The migration name may be
    given in CamelCase or under_score.

    The generator creates a migration class in db/migrate prefixed by its number
    in the queue.

Example:
    ./script/generate migration AddSslFlag

    With 4 existing migrations, this will create an AddSslFlag migration in the
    file db/migrate/005_add_ssl_flag.rb
a@a-laptop:~/only_2_m_ror$








a@a-laptop:~/only_2_m_ror$ script/generate controller

Usage: script/generate controller ControllerName [options]

Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.       

General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.     
    -q, --quiet                      Suppress normal output.            
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)

Description:
    The controller generator creates stubs for a new controller and its views.

    The generator takes a controller name and a list of views as arguments.
    The controller name may be given in CamelCase or under_score and should
    not be suffixed with 'Controller'.  To create a controller within a
    module, specify the controller name as 'module/controller'.

    The generator creates a controller class in app/controllers with view
    templates in app/views/controller_name, a helper class in app/helpers,
    and a functional test suite in test/functional.

Example:
    ./script/generate controller CreditCard open debit credit close

    Credit card controller with URLs like /credit_card/debit.
        Controller: app/controllers/credit_card_controller.rb
        Views:      app/views/credit_card/debit.rhtml [...]
        Helper:     app/helpers/credit_card_helper.rb
        Test:       test/functional/credit_card_controller_test.rb

Modules Example:
    ./script/generate controller 'admin/credit_card' suspend late_fee

    Credit card admin controller with URLs /admin/credit_card/suspend.
        Controller: app/controllers/admin/credit_card_controller.rb
        Views:      app/views/admin/credit_card/debit.rhtml [...]
        Helper:     app/helpers/admin/credit_card_helper.rb
        Test:       test/functional/admin/credit_card_controller_test.rb

a@a-laptop:~/only_2_m_ror$
a@a-laptop:~/only_2_m_ror$












@a-laptop:~/only_2_m_ror$ script/generate model

Usage: script/generate model ModelName [field:type, field:type]

Options:
        --skip-migration             Don't generate a migration file for this model

Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.       

General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)

Description:
    The model generator creates stubs for a new model.

    The generator takes a model name as its argument.  The model name may be given in CamelCase or under_score and
    should not be suffixed with 'Model'.

    As additional parameters, the generator will take attribute pairs described by name and type. These attributes will
    be used to prepopulate the migration to create the table for the model and give you a set of predefined fixture.
    You don't have to think up all attributes up front, but it's a good idea of adding just the baseline of what's
    needed to start really working with the resource.

    The generator creates a model class in app/models, a test suite in test/unit, test fixtures in
    test/fixtures/singular_name.yml, and a migration in db/migrate.

Examples:
    ./script/generate model account

        This will create an Account model:
            Model:      app/models/account.rb
            Test:       test/unit/account_test.rb
            Fixtures:   test/fixtures/accounts.yml
            Migration:  db/migrate/XXX_add_accounts.rb

    ./script/generate model post title:string created_on:date body:text published:boolean

        Creates post model with predefined attributes.
a@a-laptop:~/only_2_m_ror$
a@a-laptop:~/only_2_m_ror$










@a-laptop:~$ rails only_2_m_ror                      
      create                                          
      create  app/controllers                         
      create  app/helpers                             
      create  app/models                              
      create  app/views/layouts                       
      create  config/environments                     
      create  components                              
      create  db                                      
      create  doc                                     
      create  lib                                     
      create  lib/tasks                               
      create  log                                     
      create  public/images                           
      create  public/javascripts                      
      create  public/stylesheets                      
      create  script/performance                      
      create  script/process                          
      create  test/fixtures                           
      create  test/functional                         
      create  test/integration                        
      create  test/mocks/development                  
      create  test/mocks/test                         
      create  test/unit                               
      create  vendor                                  
      create  vendor/plugins                          
      create  tmp/sessions                            
      create  tmp/sockets                             
      create  tmp/cache                               
      create  tmp/pids                                
      create  Rakefile                                
      create  README                                  
      create  app/controllers/application.rb          
      create  app/helpers/application_helper.rb       
      create  test/test_helper.rb                     
      create  config/database.yml                     
      create  config/routes.rb                        
      create  public/.htaccess                        
      create  config/boot.rb                          
      create  config/environment.rb                   
      create  config/environments/production.rb       
      create  config/environments/development.rb      
      create  config/environments/test.rb
      create  script/about
      create  script/breakpointer
      create  script/console
      create  script/destroy
      create  script/generate
      create  script/performance/benchmarker
      create  script/performance/profiler
      create  script/process/reaper
      create  script/process/spawner
      create  script/process/inspector
      create  script/runner
      create  script/server
      create  script/plugin
      create  public/dispatch.rb
      create  public/dispatch.cgi
      create  public/dispatch.fcgi
      create  public/404.html
      create  public/500.html
      create  public/index.html
      create  public/favicon.ico
      create  public/robots.txt
      create  public/images/rails.png
      create  public/javascripts/prototype.js
      create  public/javascripts/effects.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/controls.js
      create  public/javascripts/application.js
      create  doc/README_FOR_APP
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
a@a-laptop:~$
















a@a-laptop:~/only_2_m_ror$ script/generate
Usage: script/generate generator [options] [args]

Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.

General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)


Installed Generators
  Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, scaffold_resource, session_migration, web_service

More are available at http://rubyonrails.org/show/Generators
  1. Download, for example, login_generator.zip
  2. Unzip to directory /home/a/.rails/generators/login
     to use the generator with all your Rails apps
     or to /home/a/only_2_m_ror/generators/login
     to use with this app only.
  3. Run generate with no arguments for usage information
       script/generate login

Generator gems are also available:
  1. gem search -r generator
  2. gem install login_generator
  3. script/generate login

a@a-laptop:~/only_2_m_ror$




*/

?>
